package com.dragon.queue;

/**
 * @author dragon
 * @version 1.0
 * @description 链表队列
 * @date created in 2018-12-17
 */
public class LinkedListQueue<E> implements Queue<E> {

    /**
     * 记录链表的头部
     */
    private Node<E> head;

    /**
     * 记录链表的尾部
     */
    private Node<E> tail;

    /**
     * 链表中的元素个数
     */
    private int size;

    //静态内部的Node类
    private static class Node<E> {
        E item;
        Node<E> next;

        Node(E item, Node<E> next) {
            this.item = item;
            this.next = next;
        }
    }

    /**
     * 出列
     *
     * @return
     */
    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("dequeue failed ,queue is empty");
        }
        Node<E> retNode = head;
        head = head.next;
        retNode.next = null;
        if (head == null) {
            tail = null;
        }
        size--;
        return retNode.item;
    }

    /**
     * 入列
     *
     * @param e
     */
    @Override
    public void enqueue(E e) {
        if (head == null) {
            head = tail = new Node<>(e, null);
        } else {
            tail.next = new Node<>(e, null);
            tail = tail.next;
        }
        size++;
    }

    @Override
    public int size() {
        return this.size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public E getHead() {
        if (isEmpty()) throw new IllegalArgumentException("Queue is empty.");
        return head.item;
    }
}
